package eu.vconect.orch;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

public class HangoutSession {
	private static Logger LOG = Logger.getLogger(HangoutSession.class);
	private static Map<String, HangoutSession> instance = new HashMap<String, HangoutSession>();
	private String id;
	private Map<String, Object> participantsMap;
	private Orchestrator orchestrator;
	
	private HangoutSession(String id) {
		LOG.debug("New hangout session [" + id + "]");
		this.id = id;
		participantsMap = new HashMap<String, Object>();
	}
	
	public Map<String, Object> getParticipantsMap() {
		return participantsMap;
	}
	
	public static HangoutSession instance(String url) throws MalformedURLException, URISyntaxException {
		URL key = new URL(url);
		key.toURI();		
		if (!instance.containsKey(url))
			instance.put(url, new HangoutSession(url));
		return instance.get(url);		
	}
	
	public static Set<String> instanceKeySet() {
		return instance.keySet();
	}
	
	public static void reset(String url) throws MalformedURLException, URISyntaxException {
		URL key = new URL(url);
		key.toURI();		
		if (instance.containsKey(url)) {
			LOG.debug("Delete hangout session [" + instance.get(url).id + "]");
			instance.get(url).orchestrator.stop();
			instance.remove(url);
		}
	}
	
	public static void reset() {
		for ( Iterator<String> i = instance.keySet().iterator(); i.hasNext(); ) {
			String key = i.next();
			try {
				HangoutSession.reset(key);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (URISyntaxException e) {
				e.printStackTrace();
			}
		}
		instance.clear();
		instance = null;
		LOG.debug("All sessions have been cleaned up.");
	}
	
	public Orchestrator getOrchestrator() {
		if ( orchestrator == null ) {
			orchestrator = new SimpleOrchestrator(this);
			orchestrator.start();
		}		
		return orchestrator;		
	}
}
